package com.blog.blog.service.impl;

import com.blog.blog.service.AuthService;
import com.blog.blog.service.EmailNotificationService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.core.env.Environment;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class AuthServiceImpl implements AuthService {

    private final StringRedisTemplate stringRedisTemplate;
    private final com.blog.blog.mapper.UserMapper userMapper;
    private final Environment environment;
    private final EmailNotificationService emailNotificationService;
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    public AuthServiceImpl(StringRedisTemplate stringRedisTemplate, com.blog.blog.mapper.UserMapper userMapper, Environment environment, EmailNotificationService emailNotificationService) {
        this.stringRedisTemplate = stringRedisTemplate;
        this.userMapper = userMapper;
        this.environment = environment;
        this.emailNotificationService = emailNotificationService;
    }

    @Override
    public String login(String username, String rawPassword) {
        if (username == null || username.isBlank() || rawPassword == null) return null;
        com.blog.blog.po.UserPO user = userMapper.selectByUsername(username);
        // 正常路径：存在用户且启用状态，且密码匹配
        if (user != null && (user.getStatus() == null || user.getStatus() != 0)
                && user.getPassword() != null
                && passwordEncoder.matches(rawPassword, user.getPassword())) {
            String roles = userMapper.selectRolesByUserId(user.getId());
            String token = UUID.randomUUID().toString().replaceAll("-", "");
            String key = "auth:token:" + token;
            stringRedisTemplate.opsForValue().set(key, user.getId() + "|" + (roles == null ? "" : roles), 24, TimeUnit.HOURS);
            return token;
        }
        // 开发环境兜底：admin/admin 仅在dev环境且用户不存在时生效（避免与实际密码冲突）
        if (user == null && "admin".equals(username) && "admin".equals(rawPassword)) {
            try {
                String[] profiles = environment.getActiveProfiles();
                boolean dev = false;
                if (profiles != null) {
                    for (String p : profiles) { if ("dev".equalsIgnoreCase(p)) { dev = true; break; } }
                }
                if (dev) {
                    Long userId = 1L;
                    String roles = "ADMIN";
                    String token = UUID.randomUUID().toString().replaceAll("-", "");
                    String key = "auth:token:" + token;
                    stringRedisTemplate.opsForValue().set(key, userId + "|" + roles, 24, TimeUnit.HOURS);
                    return token;
                }
            } catch (Exception ignored) {}
        }
        return null;
    }

    @Override
    public Long verify(String token) {
        if (token == null || token.isBlank()) return null;
        String v = stringRedisTemplate.opsForValue().get("auth:token:" + token);
        if (v == null) return null;
        try {
            String[] arr = v.split("\\|");
            return Long.parseLong(arr[0]);
        } catch (Exception ignored) {
            return null;
        }
    }

    @Override
    public void logout(String token) {
        if (token == null || token.isBlank()) return;
        stringRedisTemplate.delete("auth:token:" + token);
    }

    @Override
    public boolean register(com.blog.blog.dto.RegisterDTO dto) {
        if (dto == null || dto.getUsername() == null || dto.getUsername().isBlank() || dto.getPassword() == null || dto.getPassword().isBlank()) return false;
        String encoded = passwordEncoder.encode(dto.getPassword());
        int n = userMapper.insertUser(dto.getUsername(), encoded, dto.getEmail());
        if (n <= 0) return false;
        com.blog.blog.po.UserPO u = userMapper.selectByUsername(dto.getUsername());
        if (u == null) return true;
        Long roleId = userMapper.selectRoleIdByCode("USER");
        if (roleId != null) {
            try { userMapper.insertUserRole(u.getId(), roleId); } catch (Exception ignored) {}
        }
        
        // 发送欢迎邮件
        if (dto.getEmail() != null && !dto.getEmail().isEmpty()) {
            try {
                emailNotificationService.sendWelcomeEmail(dto.getEmail(), dto.getUsername());
            } catch (Exception e) {
                // 邮件发送失败不影响注册功能
                System.err.println("发送欢迎邮件失败: " + e.getMessage());
            }
        }
        
        return true;
    }
}


